package annotation.demo1;


import java.lang.reflect.Field;

public class ValidateProcessor {

    public static boolean check(Object obj) throws IllegalAccessException{
        if (obj == null) {
            System.out.println("！！校验对象为空！！");
            return false;
        }

        // 获取User类的所有属性（如果使用getFields，就无法获取到private的属性）
        Field[] fields = obj.getClass().getDeclaredFields();

        for (Field field : fields) {
            // 如果属性有注解，就进行校验
            if (field.isAnnotationPresent(Validate.class)) {
                field.setAccessible(true);
                Validate validate = field.getAnnotation(Validate.class);
                Object value = field.get(obj);
                if (validate.isNotNull() && value == null) {
                    System.out.println("field is null:" + field.getName());
                    return false;
                }

                if (value.getClass().isAssignableFrom(String.class)) {
                    String val = String.class.cast(field.get(obj));
                    if (val.length() < validate.min()) {
                        System.out.println("field length is:" + val.length());
                        return false;
                    }

                    if (val.length() > validate.max()) {
                        System.out.println("field length is:" + val.length());
                        return false;
                    }

                }
            }
        }

        return true;
    }
}
